<template>
    <div style="height: 100vh; overflow: hidden">
        <div
            style="height: 50px; line-height: 50px; border-bottom: 2px solid var(--colorRed); padding-left: 50px; color: var(--colorRed)">
          <b style="font-size: 24px;">WEBLOG</b>
          <i style="margin-left :20px">-- 只为小白的你</i>
        </div>


        <div
            style="width: 50%; margin: 100px auto;border-redius: 10px; box-shadow: 0 0 10px -2px cornflowerblue; display: flex;">

            <div style="flex: 1; padding: 100px 50px">
                <img src="../assets/imgs/写作.png" alt="" style="width: 100%;">
            </div>

            <div style="flex: 1; padding: 50px; padding-top: 120px;">
                <div class="form-toggle">
                    <b :class="{'active': activeToggle === 'account'}" @click="toggle('account')">账号登录</b>
                    <b :class="{'active': activeToggle === 'phone'}" style="margin-left: 10px"
                        @click="toggle('phone')">手机号登录</b>
                </div>

                <el-form ref="form" :rules="rules" :model="loginForm" v-show="activeToggle === 'account'"> 
                    <el-form-item prop="account">
                        <el-input size="medium" v-model="loginForm.account" prefix-icon="el-icon-user"
                                    placeholder="请输入账号/邮箱"></el-input>
                    </el-form-item>
                    <el-form-item prop="password">
                        <el-input size="medium" show-password v-model="loginForm.password" prefix-icon="el-icon-lock"
                                placeholder="请输入密码"></el-input>
                    </el-form-item>
                    <div style="margin: 10px 0; text-align: right; cursor:pointer"   @click="dialogVisible = true">
                        忘记密码
                    </div>
                    <div>
                        <el-button type="primary" size="medium" style="width: 100%" @click="login('/session/login')">登录</el-button>
                    </div>
                    <div style="margin :10px 0; text-align: right;">
                        <a href="/register" style="color:var(--colorRed)">没有账号？立即注册</a>
                    </div>
                </el-form>





                <!-- 手机号登录 -->
                <el-form ref="formPhone" :rules="rulePhone" :model="loginForm"  v-show="activeToggle === 'phone'">
                    <el-form-item prop="phone">
                        <el-input size="medium" v-model="loginForm.phone" prefix-icon="el-icon-user" placeholder="请输入手机号"></el-input>
                    </el-form-item>
                    <el-form-item prop="smsCode">
                        <div style="display: flex;">
                            <!-- flex:2 占两份 -->
                            <el-input size="medium" style="flex: 2" v-model="loginForm.smsCode"
                                        prefix-icon="el-icon-circle-check" placeholder="请输入验证码"></el-input>
                            <el-button :disabled="second > 0" size="medium" style="flex: 1;margin-left: 5px" @click="sendSMS">点击发送
                                <span v-if="second > 0">({{ second }})</span></el-button>
                        </div>
                    </el-form-item>

                    <div>
                        <el-button type="primary" size="medium" style="width:100%" @click="login('/session/loginsms')" >登录</el-button>
                    </div>

                    <div style="margin:10px 0; text-align: right;">
                        <a href="/register" style="color:var(--colorRed)">没有账号？立即注册</a>
                    </div>
                </el-form>
            </div>
        </div>

        <!-- <el-dialog v-model="passwordVis" title="忘记密码" :close-on-click-modal="false" style="width: 500px; padding: 0 20px">
            <el-form :model="passwordForm" ref="rulePasswordFormRef" :rules="passwordRules" status-icon label-width="70px">
                <el-form-item label="邮箱" prop="email">
                <el-input v-model="passwordForm.email" autocomplete="off" />
                </el-form-item>
                <el-form-item label="验证码" prop="emailCode">
                <div style="display: flex; width: 100%">
                    <el-input style="flex: 1" v-model="passwordForm.emailCode" clearable></el-input>
                    <el-button style="width: 120px; margin-left: 5px" @click="sendEmail" :disabled="time > 0">点击发送<span v-if="time">（{{ time }}）</span></el-button>
                </div>
                </el-form-item>
            </el-form>
            <template #footer>
            <span class="dialog-footer">
                <el-button @click="passwordVis = false">取消</el-button>
                <el-button type="primary" @click="resetPassword">确认</el-button>
            </span>
            </template>
        </el-dialog> -->

     

        <el-dialog 
        title="重置密码"
        :visible.sync="dialogVisible"
        width="30%"
        center>
        <span style="color:red">请输入邮箱验证</span>
        <span slot="footer" class="dialog-footer">
            <el-form :model="passwordForm" ref="rulePasswordFormRef" :rules="rulePasswordFormRef" status-icon label-width="70px">
                <el-form-item label="邮箱" prop="email">
                <el-input v-model="passwordForm.email" autocomplete="off" />
                </el-form-item>
                <el-form-item label="验证码" prop="emailcode">
                <div style="display: flex; width: 100%">
                    <el-input style="flex: 1" v-model="passwordForm.emailcode" clearable></el-input>
                    <el-button style="width: 120px; margin-left: 5px" @click="sendEmail" :disabled="second > 0">点击发送<span v-if="second > 0 ">({{ second }})</span></el-button>
                </div>
                </el-form-item>
            </el-form>
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="resetPassword">确 定</el-button>
        </span>
        </el-dialog>





    </div>
</template>


<script>
import request from '@/utils/request'

export default {
    name:"Login",
    data(){
        const checkPhone =(rule,value,callback) =>{
            if(this.validatePhone.test(value)){
                return callback(new Error('手机号格式不合法'))
            }
            callback()
        }

        const checkSMS = (rule, value, callback) => {
            if(!/\d{6}/.test(value)) {
                return callback(new Error('验证码必须是数字且长度必须是6位'));
            }
            callback()
        }

        return{
            passwordForm:{},
            loginForm:{},
            activeToggle: 'phone',
            dialogVisible: false,
            second: 0,
            rules:{
                account:[
                    {required: true,message: '请输入用户名/邮箱/手机号',trigger:'blur'}
                ],
                password: [
                    {required: true, message: '请输入密码', trigger: 'blur'},
                    {min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'}
                ]
            },


            rulesPhone:{
                phone: [
                    { validator: checkPhone, trigger: 'blur' }
                ],
                smsCode: [
                    { validator: checkSMS, trigger: 'blur' }
        
                ]
            },


            rulePasswordFormRef:{
                email: [
                    { required: true,message: '请输入邮箱',trigger:'blur' }
                ],
                emailCode: [
                    { validator: checkSMS, trigger: 'blur' }
        
                ]
            },

            // 手机号正则
            validatePhone: /^1[3,4,5,6,7,8,9][0-9]{9}$/,
            validateEmail: /^\w+@[\da-z\.-]+\.([a-z]{2,6}|[\u2E80-\u9FFF]{2,3})$/,
            interval: null

        }
    },
    methods:{
        resetPassword(){
            this.$refs["rulePasswordFormRef"].validate((valid) =>{
                if(valid){
                    request.post("/password/reset",this.passwordForm).then(res => {
                        if(res.code === '200'){
                            this.$message.success("重置密码成功,您的新密码为:" + res.data)
                            this.dialogVisible = false
                        }else{
                            this.$message.error(res.msg)
                        }
                    })
                }
            })
        },



        times(){
            // 防止点击太快 ，没来得及清理
            if(this.interval){
                clearInterval(this.interval)     
            }
            this.second = 30
            this.interval = setInterval(() => {   //如果不清理这个"线程会一直存在"，于是每次点击都会创建一个新的线程
                if(this.second > 0){
                    this.second--
                }else{
                    clearInterval(this.interval)   // 停止
                    this.interval = null
                }
            }, 1000)

        },
        toggle(active) {
            this.activeToggle = active
            // 在切换表单的时候 清空表单
            if (this.$refs.form) {
                this.$refs.form.resetFields()
            }
            if (this.$refs.formPhone) {
                this.$refs.formPhone.resetFields()
            }
            this.loginForm = {}
        },


        sendEmail(){
            //校验是否合法
            if(!this.validateEmail.test(this.passwordForm.email)) {
                this.$message.warning("邮箱格式不合法")
                return
            }
            request.get("/email",{
                params:{
                    email: this.passwordForm.email,
                    type: "RESETPASSWORD"
                }
            }).then(res => {
                if(res.code === '200'){
                    this.$message.success("发送成功,有效期五分钟")
                    this.times()
                }else{
                    this.$message.error(res.msg)
                }
            })
        },

        sendSMS(){
            //校验是否合法
            if(!this.validatePhone.test(this.loginForm.phone)) {
                this.$message.warning("手机号格式不合法")
                return
            }

            // 发送验证码
            request.get('/session/sms', {
                params: {
                    phone: this.loginForm.phone
                }
            }).then(res => {
                console.log(res)
                if (res.code === '200') {
                    this.$message.success('发送成功,有效期五分钟')
                    this.times()
                } else {
                    this.$message.warning(res.msg)
                }
            })
        },

        login(url){
            let form = 'form'
            if(!url){
                return
            }else if(url.includes('/loginsms')){
                form = 'formPhone'
            }
            //请求后台接口
            this.$refs[form].validate((valid) =>{
                if(valid){  //验证通过
                    request.post(url,this.loginForm).then(res => {
                        if(res.code === '200'){
                            // 存数据[mutations对象名，载荷]
                            this.$store.commit('setLoginData',res.data)    
                            this.$router.push('/')  // 跳转到主页
                            this.$message.success('登录成功')
                        }else{
                            this.$message.error(res.msg)
                        }
                    })

                }
            })
        }
    }
}




</script>


<style scoped>

.form-toggle {
    margin: 20px 0;
    padding-left: 50px;
    text-align: ceter;
}

.form-toggle b {
    font-size: 20px;
    cursor: pointer;
}

.active {
  color: var(--colorRed);
}
</style>


